﻿using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.XPath;

namespace Syfuhs.APIWrappers.LiveMeeting
{
    static class HttpRequestHelper
    {
        /// <summary>
        /// Gets the URL for API Posting
        /// </summary>
        /// <param name="confCenter">Name of conference center</param>
        /// <returns>Returns string URL</returns>
        public static Uri GetPostingUrlRequest(string confCenter)
        {
            return GetPostingUrlRequest(confCenter, false);
        }

        public static Uri GetPostingUrlRequest(string confCenter, bool useSsl)
        {
            Uri url = new Uri(string.Format(CultureInfo.InvariantCulture,
                "http{0}://www.livemeeting.com/cc/{1}/xml/4.0/GetPostingURLRequest", useSsl ? "s" : "", confCenter));

            XmlNode attrUrl = (GetXmlMessageRequest(url) as XmlDocument).SelectSingleNode("/PlaceWareConfCenter/GetPostingURLReply/@url");

            if (attrUrl == null)
                throw new UriFormatException();

            return new Uri(attrUrl.Value);
        }

        /// <summary>
        /// Sends an XML request to the conference center API
        /// </summary>
        /// <param name="xmldoc">XML Request</param>
        /// <returns>Returns XML Response</returns>
        public static IXPathNavigable PostXmlMessageRequest(IXPathNavigable xmlDoc, Uri postingUrl)
        {
            using (Stream respStream = PostBytes(new ASCIIEncoding().GetBytes((xmlDoc as XmlDocument).OuterXml), postingUrl))
                return ErrorHandler.CheckForError(GetXmlResponseFromStream(respStream));
        }

        /// <summary>
        /// POST a chunk of bytes to given url
        /// </summary>
        /// <param name="payload">The bytes to send</param>
        /// <param name="url">The url to send the bytes to</param>
        /// <returns>Stream response, if there is one</returns>
        public static Stream PostBytes(byte[] payload, Uri url)
        {
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
            myReq.Method = "POST";
            myReq.ContentType = "application/x-www-form-urlencoded";
            myReq.ContentLength = payload.Length;

            using (Stream reqStream = myReq.GetRequestStream())
                reqStream.Write(payload, 0, payload.Length);

            return myReq.GetResponse().GetResponseStream();
        }

        /// <summary>
        /// Create an XML GET request
        /// </summary>
        /// <param name="url">URL for XML Request</param>
        /// <returns>Returns XML Response</returns>
        public static IXPathNavigable GetXmlMessageRequest(Uri url)
        {
            using (Stream respStream = GetRequest(url))
                return ErrorHandler.CheckForError(GetXmlResponseFromStream(respStream));
        }

        public static IXPathNavigable GetXmlResponseFromStream(Stream stream)
        {
            XmlDocument response = new XmlDocument();
            response.Load(stream);

            return response;
        }

        /// <summary>
        /// Send a GET Request ot given url
        /// </summary>
        /// <param name="url">Url to GET</param>
        /// <returns>Returns response stream</returns>
        public static Stream GetRequest(Uri url)
        {
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
            myReq.Method = "GET";
            myReq.ContentType = "application/x-www-form-urlencoded";

            return myReq.GetResponse().GetResponseStream();
        }
    }
}